package com.example.xianji.adapter;

import java.io.File;
import java.util.ArrayList;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import com.example.xianji.Contant;
import com.example.xianji.R;
import com.example.xianji.bean.ReplayLouZhu;
import com.example.xianji.constant.Constant;
import com.example.xianji.single.Send_Contant;
import com.example.xianji.utils.DownLoadUtils;
import com.example.xianji.utils.DownLoadUtils.OnDownloadListener;
import com.example.xianji.eventbus.Replay_EventBus;
import com.example.xianji.utils.sp.PreferenceEngine;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.drawable.Drawable;
import android.text.Html;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class NewsReplyAdapter extends BaseAdapter {
    private Context context;
    private ArrayList<ReplayLouZhu> data;
    //    private SharedPreferences sp;
//    private Editor ed;
    private DownLoadUtils downLoadUtils;
    private int width;
    private String html = "下面是图片" +
            "<img src='http://bbs.xianjichina.com/front/kindeditor/plugins/emoticons/images/17.gif'/>";

    private final String path = "/mnt/sdcard/downimg/";

    public NewsReplyAdapter(Context context, ArrayList<ReplayLouZhu> data) {
        super();
        this.context = context;
        this.data = data;
//        sp = context.getSharedPreferences("text", context.MODE_PRIVATE);
//        ed = sp.edit();
        WindowManager wm = (WindowManager) context
                .getSystemService(Context.WINDOW_SERVICE);
        width = wm.getDefaultDisplay().getWidth();
    }

    @Override
    public int getCount() {
        return data.size();
    }

    @Override
    public Object getItem(int arg0) {
        return arg0;
    }

    @Override
    public long getItemId(int arg0) {
        return arg0;
    }

    @Override
    public View getView(int arg0, View arg1, ViewGroup arg2) {
        Holder mHolder;
        if (arg1 == null) {
            mHolder = new Holder();

            arg1 = View.inflate(context, R.layout.newsreplay_item, null);
            mHolder.replay_text = (TextView) arg1.findViewById(R.id.replay_text);
            mHolder.replay_liearlayout_zan = (LinearLayout) arg1.findViewById(R.id.replay_liearlayout_zan);
            mHolder.replay_content_text_zan = (TextView) arg1.findViewById(R.id.replay_content_text_zan);
            mHolder.repaly_huifu_time = (TextView) arg1.findViewById(R.id.repaly_huifu_time);
            arg1.setTag(mHolder);
        } else {
            mHolder = (Holder) arg1.getTag();
        }
        final int position = arg0;
        mHolder.replay_content_text_zan.setText(data.get(arg0).getPraise_count() + "");
        mHolder.repaly_huifu_time.setText(data.get(arg0).getCreated_at());

        String details = new StringBuffer(data.get(arg0).getNickname()).append(":").append(data.get(arg0).getDetails()).toString();
        //设置图文混排
        setData(mHolder.replay_text, details);
        arg1.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        v.setBackgroundColor(context.getResources().getColor(R.color.white));
                        break;

                    case MotionEvent.ACTION_UP:
                        v.setBackgroundColor(context.getResources().getColor(R.color.grayF6));
                        break;
                }

                return false;
            }


        });


        arg1.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                Send_Contant.getInstance().setReplay_click(2);
                EventBus.getDefault().postSticky(new Replay_EventBus(2, data.get(position).getNickname()));
//						EventBus.getDefault().post(new Replay_EventBus(2,data.get(position).getNickname()));

                Send_Contant.getInstance().setReply_user(data.get(position).getReplay_pinglunid());//回复人评论人ID
                Send_Contant.getInstance().setName(data.get(position).getNickname());
                Send_Contant.getInstance().setReplay_id(data.get(position).getReplay_id());//回复人ID
            }
        });
        final TextView zan_text = mHolder.replay_content_text_zan;
        mHolder.replay_liearlayout_zan.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (PreferenceEngine.getInstance().getBoolean(Constant.SP.NAME, Constant.SP.KEY_DENGLU, false)) {
                    get_replay_data(data.get(position).getPraise_id(), zan_text, data.get(position).getPraise_count());
                } else {
							/*//Intent intent=new Intent(context, Main_Login_Activity.class); 
							intent.putExtra("login_come_from", 1);
							context.startActivity(intent);*/
                }

            }
        });

        return arg1;
    }

    class Holder {
        TextView replay_content_text_zan, repaly_huifu_time;
        LinearLayout replay_liearlayout_zan;
        TextView replay_text;
    }

    public void get_replay_data(int rid, final TextView textview, final int count) {
        HttpUtils httpUtils = new HttpUtils();
        RequestParams parms = new RequestParams();
        parms.addBodyParameter("token", PreferenceEngine.getInstance().getString(Constant.SP.NAME, Constant.SP.KEY_TOKEN, ""));
        parms.addBodyParameter("rid", rid + "");

        httpUtils.send(HttpMethod.POST, Contant.news_replay, parms, new RequestCallBack<String>() {

            @Override
            public void onFailure(HttpException arg0, String arg1) {
            }

            @Override
            public void onSuccess(ResponseInfo<String> arg0) {
                try {
                    JSONObject object = new JSONObject(arg0.result);
                    //Log.i("sawwwwwww",object+"");
                    Toast.makeText(context, object.getString("msg"), Toast.LENGTH_SHORT).show();
                    if (object.getInt("status") == 1) {
                        int a = count + 1;
                        textview.setText(a + "");
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void setData(final TextView tView, final String details) {
        new File(path).mkdirs();
        //初始化下载类
        downLoadUtils = new DownLoadUtils();
        //设置下载类监听事件
        downLoadUtils.setOnDownloadListener(
                new OnDownloadListener() {

                    //下载进度
                    public void onDownloadUpdate(DownLoadUtils manager, int percent) {
                    }

                    //下载失败
                    public void onDownloadError(DownLoadUtils manager, Exception e) {

                    }

                    //开始下载
                    public void onDownloadConnect(DownLoadUtils manager) {
                    }

                    //完成下载
                    public void onDownloadComplete(DownLoadUtils manager, Object result) {
                        //替换sTExt的值，就是把图片的网络路径换成本地SD卡图片路径(最早想法，可以不需要这样做了)
                        //sText.replace(result.toString(), path+String.valueOf(result.hashCode()));
                        //再一次赋值给Textview
                        tView.setText(Html.fromHtml(details, imageGetter, null));NewsReplyAdapter.this.notifyDataSetChanged();

                    }
                }
        );
        tView.setText(Html.fromHtml(details, imageGetter, null));
    }

    final Html.ImageGetter imageGetter = new Html.ImageGetter() {
        public Drawable getDrawable(String source) {
            Drawable drawable = null;
            String fileString = path + String.valueOf(source.hashCode());
            //判断SD卡里面是否存在图片文件
            if (new File(fileString).exists()) {
                //获取本地文件返回Drawable
                drawable = Drawable.createFromPath(fileString);
                //设置图片边界
                if (drawable != null) {
                    if (width < 721) {
                        if (drawable.getIntrinsicWidth() > 300) {
                            drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
                        } else {
                            drawable.setBounds(0, 0, drawable.getIntrinsicWidth() * 3, drawable.getIntrinsicHeight() * 3);
                        }
                    } else {
                        if (drawable.getIntrinsicWidth() > 300) {
                            drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
                        } else {
                            drawable.setBounds(0, 0, drawable.getIntrinsicWidth() * 5, drawable.getIntrinsicHeight() * 5);
                        }
                    }
                }

                return drawable;
            } else {
                //Log.i("DEBUG", fileString+" Do not eixts");
                //启动新线程下载
                downLoadUtils.download(source, path + String.valueOf(source.hashCode()));
                return drawable;
            }
        }

        ;

    };
}
